package com.example.threaddemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareSource {
    private int num = 1;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print1() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (num != 1) {
                c1.await();
            }
            //2.干活

            for (int i = 0; i < 1; i++) {
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }
            //3.通知
            num = 2;
            c2.signal();

        } finally {
            lock.unlock();
        }
    }

    public void print2() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (num != 2) {
                c2.await();
            }
            //2.干活

            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }
            //3.通知
            num = 3;
            c3.signal();

        } finally {
            lock.unlock();
        }
    }

    public void print3() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (num != 3) {
                c3.await();
            }
            //2.干活

            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }
            //3.通知
            num = 1;
            c1.signal();

        } finally {
            lock.unlock();
        }
    }
}

/**
 * lock 的精准唤醒
 * A 打印 1次 ----> B打印 2次 ----> C 打印 3次 ---->
 * ----> A 打印 1次 ----> B打印 2次 ----> C 打印 3次
 * 10轮
 */
public class ConditionLockDemo {
    public static void main(String[] args) {

        ShareSource shareSource = new ShareSource();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareSource.print1();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {

                for (int i = 0; i < 10; i++) {
                    shareSource.print2();
                };
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();
        new Thread(() -> {
            try {

                for (int i = 0; i < 10; i++) {
                    shareSource.print3();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();
    }
}
